<template>
  <scroll-view class="page-scroll" scroll-y>
    <view class="container">
      <!-- 密钥验证层 -->
      <view class="key-verification" v-if="!isVerified">
        <view class="verification-card">
          <text class="verify-title">请输入开门密钥（在微信群中获取）</text>
          <input
            type="password"
            v-model="inputKey"
            placeholder="请输入密钥"
            class="key-input"
            @confirm="verifyKey"
          />
          <button class="verify-btn" @click="verifyKey">
            <text>点我验证</text>
          </button>
          <text class="author-info">作者：王里</text>
        </view>
      </view>

      <!-- 原有的计算器界面 -->
      <view class="gradient-bg" v-else>
        <view class="calculator-card">
          <view class="header">
            <text class="title">BMI计算器</text>
            <text class="author">作者：王里</text>
            <button class="logout-btn" @click="logout">
              <text>退出登录</text>
            </button>
          </view>
          
          <view class="gender-selector">
            <view 
              class="gender-option" 
              :class="{ 'selected': gender === 'male' }"
              @click="gender = 'male'"
            >
              <text class="gender-icon">👨</text>
              <text>男性</text>
            </view>
            <view 
              class="gender-option" 
              :class="{ 'selected': gender === 'female' }"
              @click="gender = 'female'"
            >
              <text class="gender-icon">👩</text>
              <text>女性</text>
            </view>
          </view>

          <view class="input-group" :class="{ 'input-focus': heightFocus }">
            <text class="label">身高 (cm)</text>
            <view class="input-wrapper">
              <input
                type="number"
                v-model="height"
                @focus="heightFocus = true"
                @blur="heightFocus = false"
                @input="handleHeightInput"
                placeholder="请输入身高"
              />
              <view class="number-animation" v-if="showHeightAnimation">
                <text :class="['bounce-text', 'bounce-up']">{{ height }}</text>
              </view>
            </view>
          </view>
          
          <view class="input-group" :class="{ 'input-focus': weightFocus }">
            <text class="label">体重 (kg)</text>
            <view class="input-wrapper">
              <input
                type="number"
                v-model="weight"
                @focus="weightFocus = true"
                @blur="weightFocus = false"
                @input="handleWeightInput"
                placeholder="请输入体重"
              />
              <view class="number-animation" v-if="showWeightAnimation">
                <text :class="['bounce-text', 'bounce-up']">{{ weight }}</text>
              </view>
            </view>
          </view>

          <button class="calculate-btn" @click="calculateBMI">
            <text>点我计算BMI</text>
          </button>

          <view v-if="bmiResult" class="result-container">
            <!-- 添加科技感动画背景 -->
            <view class="tech-background">
              <view class="tech-circle"></view>
              <view class="tech-scan"></view>
              <view class="tech-particles">
                <text v-for="n in 6" :key="n" class="particle">•</text>
              </view>
            </view>
            
            <view class="result-circle" :class="[bmiStatusClass, 'result-animate']">
              <view class="result-inner">
                <text class="bmi-label">BMI</text>
                <text class="bmi-value">{{ bmiResult.toFixed(1) }}</text>
                <text class="bmi-status">{{ getBMIStatus() }}</text>
              </view>
            </view>
            
            <view class="bmi-advice tech-text-animate">
              <text>{{ getBMIAdvice() }}</text>
            </view>
          </view>

          <view class="history-section">
            <view class="history-header">
              <text class="history-title">历史记录</text>
              <button class="clear-history-btn" @click="showClearHistoryConfirm" v-if="history.length > 0">
                <text>清除记录</text>
              </button>
            </view>
            <scroll-view class="history-list" scroll-y>
              <view 
                v-for="(record, index) in history" 
                :key="index"
                class="history-item"
                :class="{ 'fade-in': true }"
                :style="{ animationDelay: `${index * 0.1}s` }"
              >
                <view class="history-info">
                  <text>BMI: {{ record.bmi.toFixed(1) }}</text>
                  <text class="history-gender">{{ record.gender === 'male' ? '男' : '女' }}</text>
                </view>
                <text>{{ record.date }}</text>
              </view>
            </scroll-view>
          </view>
        </view>
      </view>
    </view>
  </scroll-view>
</template>

<script>
export default {
  data() {
    return {
      height: '',
      weight: '',
      gender: 'male', // 默认男性
      bmiResult: null,
      heightFocus: false,
      weightFocus: false,
      history: [],
      showHeightAnimation: false,
      showWeightAnimation: false,
      heightAnimationTimer: null,
      weightAnimationTimer: null,
      inputKey: '',
      isVerified: false,
      correctKey: '114514',
      keyEnabled: true, // 控制密钥验证是否启用
    }
  },
  computed: {
    bmiStatusClass() {
      if (!this.bmiResult) return ''
      const status = this.getBMIStatus()
      switch(status) {
        case '体重过轻': return 'status-underweight'
        case '体重正常': return 'status-normal'
        case '超重': return 'status-overweight'
        case '一级肥胖': return 'status-obese-1'
        case '二级肥胖': return 'status-obese-2'
        case '三级肥胖': return 'status-obese-3'
        default: return ''
      }
    }
  },
  methods: {
    calculateBMI() {
      if (!this.height || !this.weight || !this.gender) {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        })
        return
      }

      const heightInMeters = this.height / 100
      const bmi = this.weight / (heightInMeters * heightInMeters)
      this.bmiResult = bmi

      // 添加到历史记录
      this.history.unshift({
        bmi,
        gender: this.gender,
        date: new Date().toLocaleString()
      })

      // 保存到本地存储
      uni.setStorageSync('bmi-history', JSON.stringify(this.history))
    },
    getBMIStatus() {
      if (!this.bmiResult) return ''
      
      if (this.bmiResult < 18.5) return '体重过轻'
      if (this.bmiResult < 25.0) return '体重正常'
      if (this.bmiResult < 30.0) return '超重'
      if (this.bmiResult < 35.0) return '一级肥胖'
      if (this.bmiResult < 40.0) return '二级肥胖'
      return '三级肥胖'
    },
    getBMIAdvice() {
      const status = this.getBMIStatus()
      switch(status) {
        case '体重过轻':
          return '建议适当增加营养摄入，注意均衡饮食，适量运动增强体质。定期进行体检，必要时咨询营养师。'
        case '体重正常':
          return '恭喜！请继续保持健康的生活方式，定期运动，保持均衡饮食。建议每周运动3-5次，每次30分钟以上。'
        case '超重':
          return '建议适度控制饮食摄入，增加有氧运动，注意作息规律。可以尝试每天快走30分钟，控制碳水化合物的摄入。'
        case '一级肥胖':
          return '需要重视身体健康了！建议咨询医生制定减重计划，控制饮食，规律运动。每周至少运动5次，每次40分钟以。'
        case '二级肥胖':
          return '强烈建议在专业医生指导下进行减重！需要严格控制饮食，增加运动量，定期体检，监测各项身体指标。'
        case '三级肥胖':
          return '请立即就医！需要在专业医疗团队指导下进行综合干预治疗，可能需要考虑其他医疗措施。请严格遵医嘱！'
        default:
          return ''
      }
    },
    handleHeightInput() {
      this.showHeightAnimation = true
      clearTimeout(this.heightAnimationTimer)
      this.heightAnimationTimer = setTimeout(() => {
        this.showHeightAnimation = false
      }, 500)
    },
    handleWeightInput() {
      this.showWeightAnimation = true
      clearTimeout(this.weightAnimationTimer)
      this.weightAnimationTimer = setTimeout(() => {
        this.showWeightAnimation = false
      }, 500)
    },
    verifyKey() {
      if (!this.keyEnabled) {
        this.isVerified = true
        return
      }

      if (this.inputKey === this.correctKey) {
        this.isVerified = true
        // 可以选择将验证状态保存到本地存储
        uni.setStorageSync('bmi-verified', 'true')
      } else {
        uni.showToast({
          title: '密钥错误',
          icon: 'none'
        })
      }
    },
    
    // 提供一个方法来控制密钥验证的开关
    toggleKeyVerification(enabled) {
      this.keyEnabled = enabled
      if (!enabled) {
        this.isVerified = true
      } else {
        this.isVerified = false
      }
      // 保存开关状态
      uni.setStorageSync('bmi-key-enabled', enabled.toString())
    },
    logout() {
      uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            this.isVerified = false
            this.inputKey = ''
            // 清除验证状态
            uni.removeStorageSync('bmi-verified')
            uni.showToast({
              title: '已退出登录',
              icon: 'success'
            })
          }
        }
      })
    },
    showClearHistoryConfirm() {
      uni.showModal({
        title: '确认清除',
        content: '确定要清除所有历史记录吗？此操作不可恢复！',
        confirmColor: '#ff7675',
        success: (res) => {
          if (res.confirm) {
            this.clearHistory()
          }
        }
      })
    },
    
    clearHistory() {
      this.history = []
      uni.removeStorageSync('bmi-history')
      uni.showToast({
        title: '历史记录已清除',
        icon: 'success'
      })
    }
  },
  onLoad() {
    // 读取密钥验证开关状态
    const keyEnabled = uni.getStorageSync('bmi-key-enabled')
    if (keyEnabled !== '') {
      this.keyEnabled = keyEnabled === 'true'
    }

    // 如果密钥验证被禁用，直接显示主界面
    if (!this.keyEnabled) {
      this.isVerified = true
      return
    }

    // 读取验证状态
    const verified = uni.getStorageSync('bmi-verified')
    if (verified === 'true') {
      this.isVerified = true
    }

    // 读取历史记录
    const savedHistory = uni.getStorageSync('bmi-history')
    if (savedHistory) {
      this.history = JSON.parse(savedHistory)
    }
  }
}
</script>

<style>
/* 添加页面滚动相关样式 */
.page-scroll {
  flex: 1;
  height: 100vh;
}

.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.gradient-bg {
  min-height: 100vh;
  padding: 20px 20px 100px 20px; /* 增加底部内边距 */
  background-image: linear-gradient(45deg, #6c5ce7, #a8c0ff);
}

.calculator-card {
  background-color: #ffffff;
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.title {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30px;
  color: #2d3436;
}

.input-group {
  margin-bottom: 20px;
  border: 2px solid #dfe6e9;
  border-radius: 10px;
  padding: 10px;
  transition: all 0.3s ease;
}

.input-focus {
  border-color: #6c5ce7;
  box-shadow: 0 0 10px rgba(108, 92, 231, 0.2);
}

.label {
  font-size: 14px;
  color: #636e72;
  margin-bottom: 5px;
}

.calculate-btn {
  background-color: #6c5ce7;
  color: white;
  padding: 15px;
  border-radius: 10px;
  text-align: center;
  margin: 20px 0;
  transition: all 0.3s ease;
}

.calculate-btn:active {
  transform: scale(0.98);
  background-color: #5b4cc4;
}

.result-container {
  align-items: center;
  justify-content: center;
  margin: 20px 0;
  position: relative;
  height: 300px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 20px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.tech-background {
  position: absolute;
  width: 100%;
  height: 100%;
  align-items: center;
  justify-content: center;
  opacity: 0.7;
}

.tech-circle {
  position: absolute;
  width: 200px;
  height: 200px;
  border: 2px solid rgba(108, 92, 231, 0.3);
  border-radius: 100px;
  animation: techPulse 2s infinite;
}

.tech-scan {
  position: absolute;
  width: 200px;
  height: 200px;
  background: linear-gradient(to bottom, 
    rgba(108, 92, 231, 0) 0%,
    rgba(108, 92, 231, 0.3) 50%,
    rgba(108, 92, 231, 0) 100%);
  animation: techScan 2s infinite;
}

.tech-particles {
  position: absolute;
  width: 200px;
  height: 200px;
}

.particle {
  position: absolute;
  color: rgba(108, 92, 231, 0.8);
  opacity: 0;
  font-size: 24px;
}

.particle:nth-child(1) { animation: particleFloat 2s infinite 0.2s; top: 0; left: 50%; }
.particle:nth-child(2) { animation: particleFloat 2s infinite 0.4s; top: 20%; right: 20%; }
.particle:nth-child(3) { animation: particleFloat 2s infinite 0.6s; bottom: 20%; right: 20%; }
.particle:nth-child(4) { animation: particleFloat 2s infinite 0.8s; bottom: 0; left: 50%; }
.particle:nth-child(5) { animation: particleFloat 2s infinite 1.0s; bottom: 20%; left: 20%; }
.particle:nth-child(6) { animation: particleFloat 2s infinite 1.2s; top: 20%; left: 20%; }

.result-circle {
  width: 150px;
  height: 150px;
  border-radius: 75px;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
  opacity: 0;
  transform: scale(0.5);
  animation: resultAppear 0.5s ease-out forwards;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.result-inner {
  align-items: center;
  justify-content: center;
}

.bmi-label {
  font-size: 16px;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 8px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

.tech-text-animate {
  opacity: 0;
  transform: translateY(20px);
  animation: textSlideUp 0.5s ease-out 0.3s forwards;
}

@keyframes techPulse {
  0% { transform: scale(0.8); opacity: 0.5; }
  50% { transform: scale(1.1); opacity: 0.2; }
  100% { transform: scale(0.8); opacity: 0.5; }
}

@keyframes techScan {
  0% { transform: translateY(-100px); opacity: 0; }
  50% { opacity: 1; }
  100% { transform: translateY(100px); opacity: 0; }
}

@keyframes particleFloat {
  0% { transform: translate(0, 0); opacity: 0; }
  50% { opacity: 1; }
  100% { transform: translate(0, -20px); opacity: 0; }
}

@keyframes resultAppear {
  0% { 
    opacity: 0;
    transform: scale(0.5) rotate(-180deg);
  }
  100% { 
    opacity: 1;
    transform: scale(1) rotate(0deg);
  }
}

@keyframes textSlideUp {
  0% {
    opacity: 0;
    transform: translateY(20px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.bmi-value {
  font-size: 36px;
  font-weight: bold;
  color: white;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.bmi-status {
  font-size: 18px;
  color: white;
  margin-top: 8px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  font-weight: 500;
}

.bmi-advice {
  margin-top: 20px;
  padding: 15px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  line-height: 1.6;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(108, 92, 231, 0.3);
  color: #2d3436;
  font-size: 15px;
  width: 90%;
}

.history-section {
  margin-top: 30px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.history-header {
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.history-title {
  font-size: 18px;
  font-weight: bold;
  color: #2d3436;
}

.history-list {
  max-height: 200px;
  width: 100%;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 10px;
}

.history-item {
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid #dfe6e9;
  background-color: white;
}

.history-info {
  flex-direction: row;
  align-items: center;
  flex: 1;
}

.history-gender {
  margin-left: 10px;
  padding: 2px 8px;
  background-color: #6c5ce7;
  color: white;
  border-radius: 4px;
  font-size: 12px;
}

.history-item:last-child {
  border-bottom: none;
}

.history-list::-webkit-scrollbar {
  width: 4px;
}

.history-list::-webkit-scrollbar-thumb {
  background-color: #6c5ce7;
  border-radius: 2px;
}

.clear-history-btn {
  background-color: #ff7675;
  padding: 4px 12px;
  border-radius: 15px;
  box-shadow: 0 2px 5px rgba(255, 118, 117, 0.3);
  margin-left: 10px;
}

.clear-history-btn text {
  color: white;
  font-size: 12px;
}

.gender-selector {
  flex-direction: row;
  justify-content: space-around;
  margin-bottom: 20px;
}

.gender-option {
  flex-direction: column;
  align-items: center;
  padding: 15px;
  border-radius: 10px;
  border: 2px solid #dfe6e9;
  width: 100px;
}

.gender-option.selected {
  border-color: #6c5ce7;
  background-color: rgba(108, 92, 231, 0.1);
}

.gender-icon {
  font-size: 24px;
  margin-bottom: 5px;
}

.bmi-advice {
  margin-top: 15px;
  padding: 15px;
  background-color: rgba(108, 92, 231, 0.1);
  border-radius: 8px;
  line-height: 1.5;
}

.input-wrapper {
  position: relative;
  height: 40px;
}

.number-animation {
  position: absolute;
  top: -20px;
  right: 10px;
  pointer-events: none;
}

.bounce-text {
  font-size: 16px;
  color: #6c5ce7;
  opacity: 0;
  animation: bounceAndFade 0.5s ease-out;
}

@keyframes bounceAndFade {
  0% {
    opacity: 1;
    transform: translateY(0);
  }
  50% {
    opacity: 0.8;
    transform: translateY(-15px);
  }
  100% {
    opacity: 0;
    transform: translateY(-30px);
  }
}

/* 确保输入框样式正确 */
input {
  height: 40px;
  width: 100%;
  font-size: 16px;
  padding: 0 10px;
}

.input-group {
  position: relative;
  overflow: visible;
}

.key-verification {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(108, 92, 231, 0.1);
  backdrop-filter: blur(10px);
  align-items: center;
  justify-content: center;
}

.verification-card {
  background-color: white;
  border-radius: 20px;
  padding: 30px;
  width: 80%;
  align-items: center;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.verify-title {
  font-size: 20px;
  font-weight: bold;
  color: #2d3436;
  margin-bottom: 20px;
}

.key-input {
  width: 100%;
  height: 40px;
  border: 2px solid #dfe6e9;
  border-radius: 10px;
  padding: 0 15px;
  margin-bottom: 20px;
  font-size: 16px;
}

.verify-btn {
  background-color: #6c5ce7;
  color: white;
  padding: 12px 30px;
  border-radius: 10px;
  text-align: center;
}

.verify-btn:active {
  transform: scale(0.98);
  background-color: #5b4cc4;
}

.author {
  font-size: 14px;
  color: #636e72;
  text-align: center;
  margin-bottom: 20px;
}

.author-info {
  font-size: 12px;
  color: #636e72;
  margin-top: 15px;
}

.header {
  position: relative;
  margin-bottom: 30px;
}

.logout-btn {
  position: absolute;
  right: 0;
  top: 0;
  background-color: #ff7675;
  padding: 6px 12px;
  border-radius: 15px;
  box-shadow: 0 2px 5px rgba(255, 118, 117, 0.3);
}

.logout-btn text {
  color: white;
  font-size: 12px;
}

.logout-btn:active {
  transform: scale(0.95);
  background-color: #e66767;
}

/* 调整标题样式以适应新布局 */
.title {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  color: #2d3436;
  margin-bottom: 5px;
}

.author {
  font-size: 14px;
  color: #636e72;
  text-align: center;
  margin-bottom: 20px;
  display: block;
}

.status-underweight {
  background: linear-gradient(135deg, #74b9ff, #0984e3);
}

.status-normal {
  background: linear-gradient(135deg, #00b894, #00896c);
}

.status-overweight {
  background: linear-gradient(135deg, #fdcb6e, #e17055);
}

.status-obese-1 {
  background: linear-gradient(135deg, #e17055, #d63031);
}

.status-obese-2 {
  background: linear-gradient(135deg, #d63031, #b71540);
}

.status-obese-3 {
  background: linear-gradient(135deg, #b71540, #6c5ce7);
}

.history-header {
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.clear-history-btn {
  background-color: #ff7675;
  padding: 4px 12px;
  border-radius: 15px;
  box-shadow: 0 2px 5px rgba(255, 118, 117, 0.3);
}

.clear-history-btn text {
  color: white;
  font-size: 12px;
}

.clear-history-btn:active {
  transform: scale(0.95);
  background-color: #e66767;
}
</style> 